import os
from datetime import datetime, timedelta
import time as T
import re

import pandas as pd

def within_seven_days(log_date_str):
    # 将日志日期字符串转换为日期对象
    log_date = datetime.strptime(log_date_str, "%Y-%m-%d")
    # 获取当前日期
    current_date = datetime.now()
    # 计算日期差
    difference = current_date - log_date
    # 检查日期差是否在7天内
    if difference <= timedelta(days=7):
        return True
    else:
        return False

def write_data(logs_path):
    extracted_data = []
    for log_file in os.listdir(logs_path):
        log_time = log_file.split('.')[0].split('_')[1]
        if within_seven_days(log_time):
        # if True:
            file_path = os.path.join(logs_path, log_file)
            with open(file_path, 'r') as file:
            # with open(file_path, 'r', encoding='gbk', errors='ignore') as file:
                # 逐行读取文件内容
                for line in file:
                    pattern = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?(\S{2})不正常：(.*)"
                    match = re.search(pattern, line)
                    if match:
                        # 提取匹配到的信息
                        time = match.group(1)
                        view = match.group(2)
                        status = match.group(3)
                        extracted_data.append({'点位': view, '时间': time , '状态': status})
    return pd.DataFrame(extracted_data)

if __name__ == "__main__":
    logs_path = './logs'
    df = write_data(logs_path)
    df.sort_values('时间',ascending = False)
    print(df)
    # now = T.strftime("%Y-%m-%d %H:%M:%S", T.localtime())
    # # print(now)
    # df.to_excel(f'./logs_excel/YeWei_{now}.xlsx', index=False)